<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <title>插入排序</title>
</head>

<body>
  <script>
    /* 
     * insert: 实现插入排序
     *  @params
     *    ary [array] 需要排序的数组
     *  @return
     *    [array] 排序后的新数组
     * by chenjing on 2021/01/23
    */
    function insert(ary) {
      let handle = [];
      handle.push(ary[0]);
      for(let i = 1; i < ary.length; i++) {
        let A = ary[i];
        for(let j = handle.length - 1; j >= 0; j--) {
          let B = handle[j];
          if(A > B) {
            handle.splice(j + 1, 0, A);
            break;
          }
          if(j === 0) {
            handle.unshift(A);
          }
        }
      }
      return handle;
    }
    // let ary = [12, 8, 24, 16, 1];
    let ary = [12, 10, 24, 34, 16, 1];
    let result = insert(ary);
    console.log(result);
  </script>
</body>

</html>